﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using InfoLogic.Models;
using PagedList;
using System.Web.UI;
namespace InfoLogic.Controllers
{
    [Authorize]
    public class ProductController : Controller
    {
        private UserContext db = new UserContext();

        //
        // GET: /Product/
         
        public ActionResult Index(Business business)
        {
            String currentUserId = System.Web.Security.Membership.GetUser().ProviderUserKey.ToString();
            Business Business = db.Business.Find(business.BusinessId);
             
            var productsQuery = db.Product
                            .Where(p => p.BusinessId == Business.BusinessId);
           
             return View(productsQuery.ToList());
        }

        //
        // GET: /Product/Details/5

        public ActionResult Details(Guid id )
        {
            Product product = db.Product.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        //
        // GET: /Product/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Product/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Product product)
        {
            if (ModelState.IsValid)
            {
                String currentUserId = System.Web.Security.Membership.GetUser().ProviderUserKey.ToString();
                IQueryable<Business> businessQuery = db.Business
                                 .Where(b => b.UserId == currentUserId);
               
                Business Business = new Models.Business();
                foreach (var busi in businessQuery)
                {
                    product.ProductId = Guid.NewGuid();
                    product.BusinessId = busi.BusinessId;
                    product.Business = new HashSet<Business>();
                    db.Product.Add(product);
                }

                db.SaveChanges();
                return RedirectToAction("Index","Business");
            }

            return View(product);
        }

        //
        // GET: /Product/Edit/5

        public ActionResult Edit(Guid id)
        {
            Product product = db.Product.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        //
        // POST: /Product/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index", "Business");
            }
            return View(product);
        }

        //
        // GET: /Product/Delete/5

        public ActionResult Delete(Guid id )
        {
            Product product = db.Product.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        //
        // POST: /Product/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(Guid id)
        {
            Product product = db.Product.Find(id);
            db.Product.Remove(product);
            db.SaveChanges();
            return RedirectToAction("Index", "Business");
        }

        public ActionResult Notifier()
        {
            return View();
        }

        public ActionResult RegisterSales()
        {
            return View();
        }
        
        [Authorize]
        [HttpPost]
        public ActionResult AutoCompleter(Business business, string searchTerm = null, int page = 1)
        {
            //var model1 = from r in db.Product
            //            orderby r.productName descending
            //            where searchTerm == null || r.productName.StartsWith(searchTerm)
            //            select new ProductSaleModel
            //            {
            //                ProductId = r.ProductId,
            //                productName = r.productName,
            //                quantityOnHand = r.quantityOnHand,

            //            };
            

            //var model =
            //   db.Product
            //      .OrderByDescending(r => r.productName)
            //      .Where(r => searchTerm == null || r.productName.StartsWith(searchTerm) && r.BusinessId == Business.BusinessId)
            //      .Select(r => new ProductSaleModel
            //            {
            //                ProductId = r.ProductId,
            //                productName = r.productName,
            //                quantityOnHand = r.quantityOnHand,

            //            }).ToPagedList(page, 10);
            Business Business = db.Business.Find(business.BusinessId);
            var model =
               db.Product
                  .OrderByDescending(r => r.productName)
                  .Where(r =>  r.productName.StartsWith(searchTerm) && r.BusinessId == Business.BusinessId)
                  .Select(r => new ProductSaleModel
                        {
                            ProductId = r.ProductId,
                            productName = r.productName,
                            quantityOnHand = r.quantityOnHand,

                        }).ToPagedList(page, 10);

            if (Request.IsAjaxRequest())
            {
                return PartialView("_Products", model);
            }

            return View(model);
        }

        [Authorize]
        public ActionResult AutoCompleter(Business business, int page = 1)
        {
            //var model1 = from r in db.Product
            //            orderby r.productName descending
            //            where searchTerm == null || r.productName.StartsWith(searchTerm)
            //            select new ProductSaleModel
            //            {
            //                ProductId = r.ProductId,
            //                productName = r.productName,
            //                quantityOnHand = r.quantityOnHand,

            //            };


            //var model =
            //   db.Product
            //      .OrderByDescending(r => r.productName)
            //      .Where(r => searchTerm == null || r.productName.StartsWith(searchTerm) && r.BusinessId == Business.BusinessId)
            //      .Select(r => new ProductSaleModel
            //            {
            //                ProductId = r.ProductId,
            //                productName = r.productName,
            //                quantityOnHand = r.quantityOnHand,

            //            }).ToPagedList(page, 10);
            Business Business = db.Business.Find(business.BusinessId);
            var model =
               db.Product
                  .OrderByDescending(r => r.productName)
                  .Where(r =>  r.BusinessId == Business.BusinessId)
                  .Select(r => new ProductSaleModel
                  {
                      ProductId = r.ProductId,
                      productName = r.productName,
                      quantityOnHand = r.quantityOnHand,
                      sellingPrice = r.sellingPrice

                  }).ToPagedList(page, 10);

            if (Request.IsAjaxRequest())
            {
                return PartialView("_Products", model);
            }

            return View(model);
        }

        public ActionResult AutoComplete(string term)
        {

            var Product = db
                .Product
                .Where(p => p.productName.ToLower().Contains(term.ToLower()))
                .Take(10)
                .Select(p => p.productName).ToList();

            return Json(Product, JsonRequestBehavior.AllowGet);


        }

        //
        // GET: /Product/Sell/5

        public ActionResult Sell(Guid id)
        {
            Product product = db.Product.Find(id);

            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Sell(ProductSaleModel product, Int32 quantity = 0, decimal amounttendered = 0)
        {
            SellConfirmationViewModel SellConfirmationViewModel = new SellConfirmationViewModel();
            if (quantity <= product.quantityOnHand && amounttendered >= product.sellingPrice)
            {
                Sales sales = new Models.Sales();
                sales.SalesId = Guid.NewGuid();
                sales.DateOfSale = DateTime.Now;
                sales.productId = product.ProductId;

                Product dbProduct = db.Product.Find(product.ProductId);


                var _product = (from p in db.Product
                                where p.ProductId == product.ProductId
                                select p).FirstOrDefault();

                _product.quantityOnHand = _product.quantityOnHand - quantity;
                db.Entry(_product).State = EntityState.Modified;

                sales.userId = System.Web.Security.Membership.GetUser().ProviderUserKey.ToString();

                db.Sales.Add(sales);
                db.SaveChanges();


                SellConfirmationViewModel.amountDue = quantity * _product.sellingPrice;
                SellConfirmationViewModel.change = amounttendered - SellConfirmationViewModel.amountDue;
                SellConfirmationViewModel.quantity = quantity;
                SellConfirmationViewModel.purchasePrice = _product.sellingPrice;
                SellConfirmationViewModel.productName = _product.productName;

                String currentUserId = System.Web.Security.Membership.GetUser().ProviderUserKey.ToString();
                var _business = (from p in db.Business
                                 where p.UserId == currentUserId
                                 select p).FirstOrDefault();

                Business Business = db.Business.Find(_business.BusinessId);
                SellConfirmationViewModel.businessId = Business.BusinessId;
                if (amounttendered < SellConfirmationViewModel.amountDue)
                {
                    ModelState.AddModelError("", "please enter an amount tendered that is greater or equal to the amount due");
                }
                else
                {
                    return RedirectToAction("SellsConfirmation", SellConfirmationViewModel);
                }
                //return RedirectToAction("AutoCompleter");

                //return View("Sell");
            }

            else if (quantity == 0)
            {
                ModelState.AddModelError("", "please enter a quantity");
            }
            else if (amounttendered == 0)
            {
                ModelState.AddModelError("", "please enter an amount tendered");
            }

            else if (quantity > product.quantityOnHand)
            {
                ModelState.AddModelError("", "The Please Enter A Quantity that is less or equal to the quantity on hand.");
            }



            return View();
        }

        public ActionResult SellsConfirmation(SellConfirmationViewModel SellConfirmationViewModel)
        {
            return View(SellConfirmationViewModel);
        }

        
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}